package com.ssy.lingxi.system.service.impl;

import com.google.gson.Gson;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.paas.PassRoleControllerFeign;
import com.ssy.lingxi.platform.manage.api.feign.paas.OnlineServicePASSControllerFeign;
import com.ssy.lingxi.platform.manage.api.feign.paas.ShopPAASControllerFeign;
import com.ssy.lingxi.platform.manage.api.feign.paas.SitePAASControllerFeign;
import com.ssy.lingxi.system.model.request.MenuSourceVO;
import com.ssy.lingxi.system.model.response.GenerateBaseJsonFileVO;
import com.ssy.lingxi.system.service.IGenerateBaseJsonFileService;
import com.ssy.lingxi.system.service.MenuService;
import com.ssy.lingxi.system.service.RuleConfigurationService;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 生成基础数据JSON文件实现类
 * @author wyx
 * @version 2.0.0
 * @date 2021-12-22
 */
@Service
public class GenerateBaseJsonFileServiceImpl implements IGenerateBaseJsonFileService {
    @Resource
    private PassRoleControllerFeign passRoleControllerFeign;
    @Resource
    private ShopPAASControllerFeign shopPAASControllerFeign;
    @Resource
    private RuleConfigurationService ruleConfigurationService;
    @Resource
    private SitePAASControllerFeign sitePAASControllerFeign;
    @Resource
    private OnlineServicePASSControllerFeign onlineServicePASSControllerFeign;
    @Resource
    private MenuService menuService;


    /**
     * 生成基础配置JSON文件
     * @param id 站点ID
     * @return 响应结果
     */
    @Override
    public void baseConfigJsonFile(HttpServletRequest request, HttpServletResponse response, Long id) {
        GenerateBaseJsonFileVO fileVO = generateBaseJsonFileVO(id);

        String toJson = new Gson().toJson(fileVO);

        String fileName = "base.config.json";
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            out.write(toJson.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成基础配置TS文件
     * @param id 站点ID
     * @return 响应结果
     */
    @Override
    public void baseConfigTSFile(HttpServletRequest request, HttpServletResponse response, Long id) {
        GenerateBaseJsonFileVO fileVO = generateBaseJsonFileVO(id);

        String toJson = new Gson().toJson(fileVO);

        String url = "http://json2ts.com/Home/GetTypeScriptDefinition";
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        NameValuePair pair = new BasicNameValuePair("code", toJson);
        List<NameValuePair> params = new ArrayList<>();
        params.add(pair);
        String tsData = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            tsData = EntityUtils.toString(client.execute(httpPost).getEntity()).replaceAll("\\\\r|\\\\n", "");
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fileName = "base.config.ts";
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            out.write(tsData.substring(28, tsData.length() - 2).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 权限菜单列表JSON文件
     * @param vo 请求参数
     * @return 响应结果
     */
    @Override
    public void menuTreeJsonFile(HttpServletResponse response, MenuSourceVO vo) {
        Wrapper<List<Map<String, Object>>> menuTree = menuService.treeMenuAsMemberLogin(vo);
        String toJson = new Gson().toJson(menuTree.getData());

        String fileName = "router.config.json";
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            out.write(toJson.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成配置json文件
     * @param id 站点ID
     * @return 生成基础配置文件VO对象
     */
    private GenerateBaseJsonFileVO generateBaseJsonFileVO(Long id) {
        GenerateBaseJsonFileVO fileVO = new GenerateBaseJsonFileVO();
        HttpHeaders httpHead = new HttpHeaders();
        httpHead.set("source", "1");


        //获取用户类型、业务类型
        Wrapper<?> registerTypeMenu = passRoleControllerFeign.getRegisterTypeMenu(httpHead);
        if (registerTypeMenu.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException("获取用户类型和业务类型失败：" + registerTypeMenu.getMessage());
        }
        //根据站点id查询所有商城信息
        Wrapper<?> shopsBySite = shopPAASControllerFeign.findShopsBySiteId(id);
        if (shopsBySite.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException("获取站点Id的商城信息失败：" + shopsBySite.getMessage());
        }
        //查询站点详情
        Wrapper<?> details = sitePAASControllerFeign.details(id);
        if (details.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException("获取站点详情失败：" + details.getMessage());
        }
        //获取在线客服配置信息
        Wrapper<?> config = onlineServicePASSControllerFeign.findConfig();
        if (config.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException("获取在线客服配置信息失败：" + config.getMessage());
        }

        GenerateBaseJsonFileVO.UserType userType = new GenerateBaseJsonFileVO.UserType();
        GenerateBaseJsonFileVO.ShopInfo shopInfo = new GenerateBaseJsonFileVO.ShopInfo();
        GenerateBaseJsonFileVO.Global global = new GenerateBaseJsonFileVO.Global();

        userType.setUseType(registerTypeMenu.getData());
        fileVO.setUserRegister(userType);

        shopInfo.setShopInfo(shopsBySite.getData());
        shopInfo.setOrderMode(ruleConfigurationService.getOrderMode().getData());
        shopInfo.setOrderType(ruleConfigurationService.getOrderType().getData());
        fileVO.setWeb(shopInfo);

        global.setSiteInfo(details.getData());
        global.setImConfig(config.getData());
        fileVO.setGlobal(global);
        return fileVO;
    }
}
